/* 
 * Displaying a rotating RISCV logo
 */ 

#include "demos.h"
#include "lite_oled.h"

#include <stdio.h>
#include <libbase/uart.h>
#include <libbase/console.h>

/* The RISCV logo, with a tiny resolution
 * (remember, I only got 4Kb of RAM
 * on the IceStick !) 
 */
unsigned char logo[16][16] = {
   {7,7,7,7,7,7,5,3,3,3,3,3,3,3,3,7},
   {7,7,7,7,7,7,7,5,3,3,3,3,3,3,3,7},
   {1,1,1,1,2,7,7,7,3,3,3,3,3,3,3,7},
   {0,0,0,0,0,1,7,7,5,3,3,3,3,3,3,7},
   {0,0,0,0,0,0,7,7,6,3,3,3,3,3,6,7},
   {0,0,0,0,0,0,7,7,5,3,3,3,3,4,7,7},
   {0,0,0,0,0,2,7,7,4,3,3,3,3,7,7,7},
   {0,2,2,2,7,7,7,6,3,3,3,3,6,7,7,7},
   {0,7,7,7,7,7,6,3,3,3,3,5,7,7,2,7},
   {0,1,7,7,7,4,3,3,3,3,3,7,7,7,0,7},
   {0,0,2,7,7,6,3,3,3,3,6,7,7,1,0,7},
   {0,0,0,2,7,7,5,3,3,5,7,7,2,0,0,7},
   {0,0,0,0,7,7,7,5,4,7,7,2,0,0,0,7},
   {0,0,0,0,0,7,7,7,7,7,7,0,0,0,0,7},
   {0,0,0,0,0,1,7,7,7,7,1,0,0,0,0,7},
   {7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7}
};


// Macro version of oled_RGB_to_uint16() needed for
// static initialization of cmap.
#define OLED_RGB_TO_UINT16(R,G,B) \
   ((((((R) & 0xF8) << 5) | ((G) & 0xF8)) << 3) | ((B) >> 3))


/* 
 * The colormap.
 */ 
uint16_t cmap[8] = {
   OLED_RGB_TO_UINT16(0x28,0x33,0x74),
   OLED_RGB_TO_UINT16(0x7B,0x80,0x9B),
   OLED_RGB_TO_UINT16(0xAA,0xAC,0xBC),
   OLED_RGB_TO_UINT16(0xF9,0xB1,0x15),
   OLED_RGB_TO_UINT16(0xF9,0xBE,0x65),
   OLED_RGB_TO_UINT16(0xF9,0xC7,0x82),
   OLED_RGB_TO_UINT16(0xFC,0xD8,0xB0),
   OLED_RGB_TO_UINT16(0xFA,0xFB,0xF8)
};

/*
 * Generated by TOOLS/make_sintab.c
 */

int sintab[64] = {
   0,25,49,74,97,120,142,162,181,197,212,225,236,244,251,254,
   256,254,251,244,236,225,212,197,181,162,142,120,97,74,49,25,
   0,-25,-49,-74,-97,-120,-142,-162,-181,-197,-212,-225,-236,-244,
   -251,-254,-256,-254,-251,-244,-236,-225,-212,-197,-181,-162,
   -142,-120,-97,-74,-49,-25
};


static void oled_riscv_logo(int nb_args, char** args) {
    oled_init();
    puts("Press any key to exit");
    int frame = 0;
    for(;;) {
	oled_write_window(0,0,OLED_WIDTH-1,OLED_HEIGHT-1);
       
        int scaling = sintab[frame&63]+400;
        int Ux = scaling*sintab[frame & 63];         
        int Uy = scaling*sintab[(frame + 16) & 63];  
        int Vx = -Uy;                                
        int Vy =  Ux;                                

        int X0 = -(OLED_WIDTH/2)*(Ux+Vx); 
        int Y0 = -(OLED_HEIGHT/2)*(Uy+Vy);
       
	for(int y=0; y<OLED_HEIGHT; ++y) {
	    int X = X0;
	    int Y = Y0;
	    for(int x=0; x<OLED_WIDTH; ++x) {
	        unsigned char col = logo[(Y >> 18)&15][(X >> 18)&15];
	        oled_data_uint16(cmap[col]);
	        X += Ux;
	        Y += Uy;
	    }
	    X0 += Vx;
	    Y0 += Vy;
	}
       if (readchar_nonblock()) {
	  getchar();
	  break;
       }
	++frame;
    }
    oled_off();
}

#ifdef CSR_OLED_SPI_BASE
define_demo(oled_riscv_logo, "Animated RISC-V logo on OLED screen");
#endif
